//
//  RemoteView.m
//  OMG
//
//  Created by Burn on 2019/7/8.
//  Copyright © 2019 menksoft. All rights reserved.
//



#import "RemoteView.h"
#import "RemotePlayer.h"
#import "MenkSlider.h"
#import "SeekToProgress.h"
#import <AVFoundation/AVFoundation.h>
#import "Macro.h"
#import "UIView+Extension.h"
#import "PlaceholderView.h"
#import <AFNetworking.h>
@interface RemoteView ()<PlaceholderViewDelegate,UIGestureRecognizerDelegate>

@property(weak,nonatomic)AVPlayerLayer *player;
//@property(weak,nonatomic)AVPlayerLayer *subPlayer;
@property(strong,nonatomic) NSURL *url;
@property(assign,nonatomic) BOOL policy;
@property(strong,nonatomic) UIView *topView;
@property(strong,nonatomic) UIView *bottomView;
@property(strong,nonatomic) UIButton *back;
@property(strong,nonatomic) UIButton *shared;
@property(strong,nonatomic) UIButton *play;
@property(strong,nonatomic) UILabel *currentT;
@property(strong,nonatomic) MenkSlider *slider;
@property(strong,nonatomic) UILabel *totalT;
@property(strong,nonatomic) UIButton *fullScreen;
@property(strong,nonatomic) UIProgressView *loadPro;
@property(strong,nonatomic) NSTimer *timer;
@property(assign,nonatomic) BOOL userPause;
@property(assign,nonatomic) BOOL userTouching;  // 避免滑动的时候隐藏toolBar
@property(strong,nonatomic) NSTimer *hiddenTimer;
@property(assign,nonatomic) NSInteger hiddenTime;
@property(assign,nonatomic) CGPoint lastTimePoint;
@property(assign,nonatomic) CGFloat playerPorgress;
@property(strong,nonatomic) SeekToProgress *stp;
@property(assign,nonatomic) NSInteger totalTime;
@property(assign,nonatomic) CGFloat panProgress;
@property(assign,nonatomic) BOOL playEnd;
@property(assign,nonatomic) BOOL playing;
@property(strong,nonatomic) PlaceholderView *messageLabel;




@end

@implementation RemoteView

- initWith:(NSURL *)url cachePolicy:(BOOL)policy frame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.url = url;
        self.policy = policy;
        [[RemotePlayer shared]playWith:url cachePolicy:policy];

        
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(statuChange:) name:PLAYSTATUCHANGEKEY object:nil];
        
        UITapGestureRecognizer *labelTapGestureRecognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(animatedToolBar)];
        [self addGestureRecognizer:labelTapGestureRecognizer];
        
    
        UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanFrom:)];
        pan.delegate = self;
        [self addGestureRecognizer:pan];
        
        self.lastTimePoint = CGPointZero;
        
        [self upui];
        
        [self.topView addObserver:self forKeyPath:@"alpha" options:NSKeyValueObservingOptionNew context:nil];
    }
    return self;
}

#pragma mark - UIPanGestureRecognizer和slider冲突
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if ([touch.view isKindOfClass:[UISlider class]]) {
        // cell 不需要响应 父视图的手势，保证didselect 可以正常
        return NO;
    }
    //默认都需要响应
    return  YES;
}

#pragma mark - 自动隐藏ToolBar
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"alpha"]) {
        if ([change[@"new"] integerValue] == 1) {
            self.hiddenTime = 0;
            [self hiddenToolBar];
        }
    }
}


- (void)hiddenToolBar{
    
    [self.hiddenTimer invalidate];
    self.hiddenTimer = nil;
    
    self.hiddenTimer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
        self.hiddenTime += 1;
        if (self.hiddenTime >= 5 && !self.userTouching) {
            [self animatedToolBar];
            [self.hiddenTimer invalidate];
            self.hiddenTimer = nil;
        }
    }];
}

- (void)handlePanFrom:(UIPanGestureRecognizer *)recognizer{

    if(self.playEnd || !self.playing){return;}
    
    CGPoint p = [recognizer locationInView:self];
    CGFloat x = self.lastTimePoint.x - p.x;

    switch (recognizer.state) {
        case UIGestureRecognizerStateBegan:
            self.lastTimePoint = p;
            self.playerPorgress = [[RemotePlayer shared] progress];
            self.totalTime = [[RemotePlayer shared]totalTime];
            self.stp = [[SeekToProgress alloc]initWithFrame:CGRectZero pro:0 total:[[RemotePlayer shared]totalTimeFormat]];
            self.stp.hidden = YES;
            [self addSubview:self.stp];
            break;
        case UIGestureRecognizerStateChanged:
            if (x > 0) {
                //  往左
                CGFloat w = self.lastTimePoint.x - p.x;
                self.panProgress =  self.playerPorgress - w / self.width;
                self.panProgress = self.panProgress < 0 ? 0 : self.panProgress;
                DLOG(@"左%f",self.panProgress);
                self.stp.progress = self.panProgress;
                if (self.panProgress < 0) {return;}
                if (self.stp.hidden) {self.stp.hidden = NO;}
                NSInteger currentTime = self.panProgress * self.totalTime;
                self.stp.times = [NSString stringWithFormat:@"%02zd:%02zd",currentTime / 60,(currentTime % 60)];
            }else{
                //  往右
                CGFloat w = p.x - self.lastTimePoint.x;
                self.panProgress =  self.playerPorgress + w / self.width;
                
                self.panProgress = self.panProgress < 0 ? 0 : self.panProgress;
                self.panProgress = self.panProgress > 1 ? 1 : self.panProgress;
                
                if (self.stp.hidden) {self.stp.hidden = NO;}
                self.stp.progress = self.panProgress;
                NSInteger currentTime = self.panProgress * self.totalTime;
                self.stp.times = [NSString stringWithFormat:@"%02zd:%02zd",currentTime / 60,(currentTime % 60)];
                DLOG(@"差值 = %f, 播放进度 = %f 计算出的progress = %f",w,self.playerPorgress,self.panProgress);
            }
            break;
        case UIGestureRecognizerStateRecognized:
            if (!self.stp.hidden) {
                self.panProgress = self.panProgress < 0 ? 0 : self.panProgress;
                self.panProgress = self.panProgress > 1 ? 1 : self.panProgress;
                [[RemotePlayer shared]playWithProgress:self.panProgress];
                self.slider.value = self.panProgress;
                NSInteger currentTime = self.panProgress * self.totalTime;
                self.currentT.text = [NSString stringWithFormat:@"%02zd:%02zd",currentTime / 60,(currentTime % 60)];
//                self.currentT.text = [NSString stringWithFormat:@"%02zd:%02zd",(currentTime / 60) < 0 ? 0 : currentTime / 60,(currentTime % 60) < 0 ? 0 : (currentTime % 60)];
            }
            [self.stp removeFromSuperview];
            self.stp = nil;
            
            break;
            
        default:
            break;
    }
    
}

- (void)animatedToolBar{
    
    if (self.topView.alpha > 0) {
        
        [UIView animateWithDuration:.5 animations:^{
            self.topView.alpha = 0;
            self.bottomView.alpha = 0;
        }];
    }else{
        [UIView animateWithDuration:.5 animations:^{
            self.topView.alpha = 1;
            self.bottomView.alpha = 1;
        }];
    }
    
    if (self.fullScreen.selected && self.topView.alpha == 0) {
        UIView *statusBar = [[UIApplication sharedApplication] valueForKey:@"statusBar"];
        CGRect statuFrame = [[UIApplication sharedApplication]statusBarFrame];
        
        [UIView animateWithDuration:.5 animations:^{
            statusBar.frame = CGRectMake(0,-50,statuFrame.size.width ,statusBar.size.height);
        }];
    }else{
        UIView *statusBar = [[UIApplication sharedApplication] valueForKey:@"statusBar"];
        CGRect statuFrame = [[UIApplication sharedApplication]statusBarFrame];
        [UIView animateWithDuration:.5 animations:^{
            statusBar.frame = CGRectMake(0,0,statuFrame.size.width ,statusBar.size.height);
        }];
    }
    
}

- (void)upui{
    
    self.player = [AVPlayerLayer playerLayerWithPlayer:[RemotePlayer shared].player];
    self.player.backgroundColor = [UIColor blackColor].CGColor;
    [self.layer addSublayer:self.player];
    
    
    self.topView = [[UIView alloc]init];
    self.topView.backgroundColor = [[UIColor darkGrayColor] colorWithAlphaComponent:.4];
    [self addSubview:self.topView];
    self.bottomView = [[UIView alloc]init];
    self.bottomView.backgroundColor = [[UIColor darkGrayColor] colorWithAlphaComponent:.4];
    [self addSubview:self.bottomView];
    
    self.back = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.back setImage:[UIImage imageNamed:@"player_fullBack_iphone_20x40_"] forState:UIControlStateNormal];
    [self.back addTarget:self action:@selector(playerBackCLick) forControlEvents:UIControlEventTouchUpInside];
    [self.topView addSubview:self.back];
    
    self.shared = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.shared setImage:[UIImage imageNamed:@"play_share_40x40_"] forState:UIControlStateNormal];
    [self.shared addTarget:self action:@selector(sharedClick) forControlEvents:UIControlEventTouchUpInside];
    [self.topView addSubview:self.shared];
    
    self.play = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.play setImage:[UIImage imageNamed:@"player_full_pause_iphone_30x30_"] forState:UIControlStateNormal];
    [self.play setImage:[UIImage imageNamed:@"player_full_play_iphone_30x30_"] forState:UIControlStateSelected];
    [self.play addTarget:self action:@selector(playBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:self.play];
    
    self.currentT = [[UILabel alloc]init];
    self.currentT.text = @"00:00";
    self.currentT.textColor = [UIColor whiteColor];
    self.currentT.adjustsFontSizeToFitWidth = YES;
    [self.bottomView addSubview:self.currentT];
    
    self.totalT = [[UILabel alloc]init];
    self.totalT.text = @"00:00";
    self.totalT.textColor = [UIColor whiteColor];
    self.totalT.adjustsFontSizeToFitWidth = YES;
    [self.bottomView addSubview:self.totalT];
    
    self.fullScreen = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.fullScreen setImage:[UIImage imageNamed:@"play_full_iphone_40x40_"] forState:UIControlStateNormal];
    [self.fullScreen setImage:[UIImage imageNamed:@"play_mini_iphone_80x80_"] forState:UIControlStateSelected];
    [self.fullScreen addTarget:self action:@selector(fullSecreenClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:self.fullScreen];
    
    self.slider = [[MenkSlider alloc]init];
    [self.slider setThumbImage:[UIImage imageNamed:@"player_full_slider_iphone_12x15_"] forState:UIControlStateNormal];
    self.slider.tintColor = [UIColor cyanColor];
    self.slider.maximumTrackTintColor = [UIColor clearColor];
    [self.slider addTarget:self action:@selector(sliderClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.slider addTarget:self action:@selector(sliderValueChange:) forControlEvents:UIControlEventValueChanged];
    [self.slider addTarget:self action:@selector(sliderTouchDown:) forControlEvents:UIControlEventTouchDown];
    self.slider.changeValue = ^(CGFloat v) {
        // !!!:这个时候 不需要对timer进行操作,因为音频决定跳转的那一刻,时间已经改变
        [[RemotePlayer shared]playWithProgress:v];
    };
    
    self.loadPro = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleDefault];
    self.loadPro.tintColor = [UIColor lightGrayColor];
    self.loadPro.progress = 0;
    
    [self.bottomView addSubview:self.loadPro];
    [self.bottomView addSubview:self.slider];
    
    [self addSubview:self.messageLabel];
}


- (void)layoutSubviews{
    [super layoutSubviews];

    CGFloat w = [[UIApplication sharedApplication] statusBarFrame].size.width;
    self.player.frame = CGRectMake(0, 0, w, SCREEN_WIDTH * 9/16);
    self.topView.frame = CGRectMake(0, 0, w, w > 450 ? 40 + 30 : 55);
    self.back.frame = CGRectMake(5, self.topView.frame.size.height - 35, 30, 35);
    self.shared.frame = CGRectMake(w - 40, self.topView.frame.size.height - 35, 30, 35);
    
    self.bottomView.frame = CGRectMake(0, w > 450 ? self.frame.size.width - 50 : self.frame.size.height - 50, w, 50);
    self.play.frame = CGRectMake(5, 5, 30, 30);
    self.currentT.frame = CGRectMake(45, 5, 30, 30);
    self.slider.frame = CGRectMake(90, 13, w - 180, 20);
    self.totalT.frame = CGRectMake(w - 80, 5, 30, 30);
    self.fullScreen.frame = CGRectMake(w - 45,6, 30, 30);
    self.loadPro.frame = [self.slider trackRectForBounds:self.slider.bounds];
    self.loadPro.center = self.slider.center;
    self.stp.frame = CGRectMake( SCREEN_WIDTH * .5 - 150 * .5, w > 450 ? SCREEN_HEIGHT * .5 - 25 * .5 :  self.height * .5 - 25 * .5, 150, 50);
    self.messageLabel.center = CGPointMake( w > 450 ? SCREEN_WIDTH * .5 : self.center.x,w > 450 ? SCREEN_HEIGHT * .5 : self.bounds.size.height * .5);
    
}

- (void)playerBackCLick{
    [[NSNotificationCenter defaultCenter]postNotificationName:PLAYBACK object:nil];
}

- (void)sharedClick{
    [[NSNotificationCenter defaultCenter]postNotificationName:RiGHTTOPCLICK object:nil];
}

- (void)sliderClick:(UISlider *)slider{
    [[RemotePlayer shared]playWithProgress:slider.value];
    self.userTouching = NO;
    DLOG(@"UpInside");
}

- (void)sliderValueChange:(UISlider *)slider{
    self.userTouching = YES;
    DLOG(@"valueChange");
}

- (void)sliderTouchDown:(UISlider *)slider{
//    UIView *tempView = [self snapshotViewAfterScreenUpdates:NO];
    DLOG(@"toucheDown");
}

- (void)useTimer{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
        self.currentT.text = [[RemotePlayer shared]currentTimeFormat];
        self.totalT.text = [[RemotePlayer shared]totalTimeFormat];
        if (!self.userTouching) {
            self.slider.value = [[RemotePlayer shared]progress];
        }
        self.loadPro.progress = [[RemotePlayer shared]loadProgress];
    }];
}

- (void)statuChange:(NSNotification *)center{
    NSDictionary *info = center.userInfo;
    NSInteger value = [info[@"value"] integerValue];
    switch (value) {
        case Loading:
            self.messageLabel.hidden = NO;
            [self.messageLabel holder];

            break;
        case ReadyToPlay:

            self.playEnd = NO;
            [self useTimer];
            // !!!: 隐藏toolBar
            [self animatedToolBar];
            break;
        case Failed:
            self.play.selected = NO;
            break;
        case Play:
            self.messageLabel.hidden = NO;
            [self.messageLabel removeFromSuperview];
            self.messageLabel = nil;
            self.playing = YES;
            // !!!: 用户暂停的情况下不改变状态
            if (!self.userPause) {
                self.play.selected = YES;
            }
            break;
        case PlayEnd:
            self.play.selected = NO;
            [self.timer invalidate];
            self.timer = nil;
            self.playEnd = YES;
            break;
        case PayPaused:
            // !!!: 播放被打断
            self.playing = NO;
            self.play.selected = NO;
            break;
        default:
            break;
    }
}

- (void)NetworkStatuChange{
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    // 2.设置网络状态改变后的处理
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态改变了, 就会调用这个block
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
                DLOG(@"未知网络");
                break;
                
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                DLOG(@"没有网络(断网)");
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                [[NSNotificationCenter defaultCenter]postNotificationName:FULLSCREENCLICK object:nil];
                DLOG(@"手机自带网络");
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                DLOG(@"WIFI");
                break;
        }
    }];
    
    // 3.开始监控
    [manager startMonitoring];
}

- (void)playBtnClick:(UIButton *)btn{
    if (btn.selected) {
        [[RemotePlayer shared] pause];
        btn.selected = NO;
        [self.timer invalidate];
        self.timer = nil;
        self.userPause = YES;
    }else{
        [[RemotePlayer shared] play];
        [self useTimer];
        btn.selected = YES;
        self.userPause = NO;
    }
}

- (void)fullSecreenClick:(UIButton *)btn{
    btn.selected = !btn.selected;
    [[NSNotificationCenter defaultCenter]postNotificationName:FULLSCREENCLICK object:nil];
}

- (void)removeFromSuperview{
    [super removeFromSuperview];
    [self.timer invalidate];
    self.timer = nil;
}
#pragma mark - PlaceholderViewDelegate
- (void)replayClick{
    // !!!: 重播
    
}

- (void)tryAgainClick{
    // !!!: 播放失败重试
}

- (void)resumeClick{
    // !!!: 继续
}


- (PlaceholderView *)messageLabel{
    if (!_messageLabel) {
        _messageLabel = [[PlaceholderView alloc]init];
        _messageLabel.hidden = YES;
        _messageLabel.delegate = self;
        _messageLabel.backgroundColor = [UIColor clearColor];
        _messageLabel.frame = CGRectMake(0, 0, self.bounds.size.width - 100, self.bounds.size.height - 100);
        _messageLabel.center = CGPointMake(self.center.x, self.bounds.size.height * .5);
    }
    return _messageLabel;
}



- (void)dealloc{
    [[RemotePlayer shared]stop];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    DLOG(@"RemoteView.h - dealloc");
}

@end
